package com.changgou.system.search.controller;

import com.changgou.system.entity.Page;
import com.changgou.system.search.pojo.SkuInfo;
import com.changgou.system.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/search")
public class SearchController {
@Autowired
    private SearchService searchService;



@GetMapping("/list")
public  String list(@RequestParam Map<String,String> searchMap, Model model){
   //获取数据
    this.handlerSearchMap(searchMap);
    Map searchResult = searchService.search(searchMap);
    //添加数据
    model.addAttribute("result",searchResult);
    model.addAttribute("searchMap",searchMap);



    // 封装分页数据，并返回
    //总记录数
    // 当前页
    // 每页几条
    Page<SkuInfo> page = new Page<>(
            Long.parseLong(String.valueOf(searchMap.get("total"))),
            Integer.parseInt(String.valueOf(searchMap.get("pageNum"))),
            Page.pageSize
    );
    model.addAttribute("page", page);



    //保存url
    StringBuilder url=new StringBuilder("/search/list");
    if(searchMap !=null && searchMap.size()>0){
          url.append("?");
        for (String key : searchMap.keySet()) {
           if(!key.equals("sortRule")&& !key.equals("sortFiled")&& !key.equals("pageNum")){
               url.append(key).append("=").append(searchMap.get(key)).append("&");
           }

        }
         String urlString = url.toString();
          urlString=urlString.substring(0,urlString.length()-1);

          model.addAttribute("url",urlString);
    }else {
        model.addAttribute("url",url.toString());
    }

    return "search";

}





@GetMapping
@ResponseBody
public Map search(@RequestParam Map<String,String> searchMap){
    this.handlerSearchMap(searchMap);

    Map searchResult = searchService.search(searchMap);


 return searchResult;

}


//对搜索入参带有特殊符号进行处理
 private void handlerSearchMap(Map<String,String> searchMap){
    if(null != searchMap){
        Set<Map.Entry<String, String>> entries = searchMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            if(entry.getKey().startsWith("spec_")){
                searchMap.put(entry.getKey(),entry.getValue().replace("+","%2B"));
            }
        }
    }
}
}
